package springboot.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import springboot.service.TestService;
import springboot.util.RedisUtil;

import javax.imageio.ImageIO;


import com.google.code.kaptcha.impl.DefaultKaptcha;

@Controller
public class TestController {
	private Logger log = LoggerFactory.getLogger(TestController.class);
	
	@Resource
	private TestService testService;
	@Resource
	private DefaultKaptcha captchaProducer;
	@Resource
	private JavaMailSender mailSender;
	/**
     * 获取验证码 的 请求路径
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")  
    public void defaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{  
            byte[] captchaChallengeAsJpeg = null;    
             ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();    
             try {    
             //生产验证码字符串并保存到session中  
             String createText = captchaProducer.createText();  
             httpServletRequest.getSession().setAttribute("verifyCode", createText);  
             //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中  
             BufferedImage challenge = captchaProducer.createImage(createText);  
             ImageIO.write(challenge, "jpg", jpegOutputStream);  
             } catch (IllegalArgumentException e) {    
                 httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);    
                 return;    
             }   

             //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组  
             captchaChallengeAsJpeg = jpegOutputStream.toByteArray();    
             httpServletResponse.setHeader("Cache-Control", "no-store");    
             httpServletResponse.setHeader("Pragma", "no-cache");    
             httpServletResponse.setDateHeader("Expires", 0);    
             httpServletResponse.setContentType("image/jpeg");    
             ServletOutputStream responseOutputStream =    
                     httpServletResponse.getOutputStream();    
             responseOutputStream.write(captchaChallengeAsJpeg);    
             responseOutputStream.flush();    
             responseOutputStream.close();    
    }  

	@RequestMapping("/test")
	@ResponseBody
	public String test() {
		log.info("test");
		return "test=" + testService.getTest(1);
	}

	@RequestMapping("test2")
	public String test2(String username, Model model) {
		log.info("test2 controller");
		if("root".equals(username))
			throw new RuntimeException("测试异常");
		model.addAttribute("username", username);
		// 
		return "test2";
	}
	 @RequestMapping("/login")
	    public String login(String verifyCode,HttpSession session,Model model){
	    	String code=(String)session.getAttribute("verifyCode");
	    	try {
	    		if(code!=null  && code.equals(verifyCode)){
	    			
	    			SimpleMailMessage message = new SimpleMailMessage();
	    			message.setFrom("1372198079@qq.com");
	    			message.setTo("1151109407@qq.com");
	    			message.setSubject("主题：简单邮件");
	    			message.setText("测试邮件内容");
	    	 
	    			mailSender.send(message);

	        		model.addAttribute("username", "邮件已发送");
	        	}else{
	        		model.addAttribute("username", "您输入的验证码有误");
	        	}
			} catch (Exception e) {
				e.printStackTrace();
			}
	    	
	    	return "test2";
	    }
	    
	@Resource
	RedisUtil redisUtil;
	
	@RequestMapping("test3")
	public String test3(String val) {
		String key = "key";
		if(redisUtil.exists(key)) {
			log.info("取出key=" + redisUtil.get(key));
		} else {
			log.info("将值存入 key");
			redisUtil.set(key, val);
		}
		return "test2";
	}
	
   
}


